package com.test.mq;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * Created by hehr on 16-6-7.
 */
public class WechatHandler extends HandlerFactory {

	private Queue<Message> wechatMsaageQueue;
	public static WechatHandler mInstance;

	public static synchronized WechatHandler getInstance() {

		if (mInstance == null) {
			mInstance = new WechatHandler();
		}

		return mInstance;
	}

	private WechatHandler() {
		wechatMsaageQueue = new LinkedList<Message>();// 单例模式保证内部只维护一个消息处理队列
	}

	@Override
	public boolean addMessage(Message msg) {
		if (msg != null) {
			boolean f = wechatMsaageQueue.offer(msg);
			return f;
		}
		return false;
	}

	@Override
	public Message handTopMessage() {
		if (wechatMsaageQueue != null) {
			return wechatMsaageQueue.poll();
		}
		return null;
	}

	@Override
	public List<Message> loopMessage() {
		if (wechatMsaageQueue == null || wechatMsaageQueue.size() == 0) {
			return null;
		}

		List<Message> msgs = new ArrayList<Message>();
		while (wechatMsaageQueue.peek() != null) {
			msgs.add(wechatMsaageQueue.poll());
		}
		return msgs;
	}

	@Override
	public boolean clearMessageQueue() {
		if (wechatMsaageQueue == null) {
			return false;
		}
		while (wechatMsaageQueue.peek() != null) {
			wechatMsaageQueue.poll();
		}
		return true;
	}
}